package com.chatbot.service;

import com.chatbot.dto.*;
import com.chatbot.entity.Character;
import com.chatbot.entity.CharacterConversation;
import com.chatbot.entity.CharacterMessage;
import com.chatbot.entity.User;
import com.chatbot.repository.CharacterRepository;
import com.chatbot.repository.CharacterConversationRepository;
import com.chatbot.repository.CharacterMessageRepository;
import com.chatbot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CharacterChatService {
    
    @Autowired
    private CharacterRepository characterRepository;
    
    @Autowired
    private CharacterConversationRepository conversationRepository;
    
    @Autowired
    private CharacterMessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private QwenApiService qwenApiService;

    @Autowired
    private TTSService ttsService;

    @Value("${dashscope.api.key}")
    private String apiKey;

    // 创建新对话
    @Transactional
    public CharacterConversationDTO createConversation(Long userId, Long characterId, String title, String sceneContext) {
        Character character = characterRepository.findByUser_IdAndCharacterId(userId, characterId);
        if (character == null) {
            throw new RuntimeException("角色不存在");
        }

        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));

        CharacterConversation conversation = new CharacterConversation();
        conversation.setUser(user);
        conversation.setCharacter(character);
        conversation.setTitle(title);
        conversation.setSceneContext(sceneContext);

        CharacterConversation savedConversation = conversationRepository.save(conversation);
        return convertToConversationDTO(savedConversation, character);
    }

    // 发送消息并获取角色回复
    @Transactional
    public CharacterChatResponse sendMessage(Long userId, CharacterChatRequest request) {
        // 验证对话存在
        CharacterConversation conversation;
        if (request.getConversationId() == null) {
            // 创建新对话
            Character character = characterRepository.findByUser_IdAndCharacterId(userId, request.getCharacterId());
            if (character == null) {
                throw new RuntimeException("角色不存在");
            }
            User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

            conversation = new CharacterConversation();
            conversation.setUser(user);
            conversation.setCharacter(character);
            conversation.setTitle("新对话");
            conversation.setSceneContext(request.getSceneContext());
            conversation = conversationRepository.save(conversation);
        } else {
            conversation = conversationRepository.findByUser_IdAndCharacterConversationId(userId, request.getConversationId());
            if (conversation == null) {
                throw new RuntimeException("对话不存在");
            }
        }

        // 保存用户消息
        CharacterMessage userMessage = new CharacterMessage();
        userMessage.setCharacterConversation(conversation);
        userMessage.setSenderType(CharacterMessage.SenderType.user);
        userMessage.setContent(request.getMessage());
        messageRepository.save(userMessage);

        // 获取角色信息
        Character character = conversation.getCharacter();
        
        // 构建角色设定和对话历史
        String characterPrompt = buildCharacterPrompt(character);
        List<CharacterMessage> historyMessages = messageRepository.findByCharacterConversation_CharacterConversationIdOrderByTimestamp(conversation.getCharacterConversationId());
        String conversationHistory = buildConversationHistory(historyMessages);

        // 调用AI模型获取回复
        String aiResponse = callQwenPlusCharacter(characterPrompt, conversationHistory, request.getMessage());

        // 生成语音
        String audioUrl = null;
        try {
            audioUrl = ttsService.generateSpeech(aiResponse, character);
        } catch (Exception e) {
            // 如果语音生成失败，记录错误但不影响文本回复
            System.err.println("语音生成失败: " + e.getMessage());
        }

        // 保存角色回复
        CharacterMessage characterMessage = new CharacterMessage();
        characterMessage.setCharacterConversation(conversation);
        characterMessage.setSenderType(CharacterMessage.SenderType.character);
        characterMessage.setContent(aiResponse);
        characterMessage.setAudioUrl(audioUrl);
        messageRepository.save(characterMessage);

        // 构建响应
        CharacterChatResponse response = new CharacterChatResponse();
        response.setConversationId(conversation.getCharacterConversationId());
        response.setMessage(aiResponse);
        response.setAudioUrl(audioUrl);
        response.setSenderType("character");
        response.setTimestamp(System.currentTimeMillis());

        return response;
    }

    // 获取对话历史
    public CharacterConversationDTO getConversation(Long userId, Long conversationId) {
        CharacterConversation conversation = conversationRepository.findByUser_IdAndCharacterConversationId(userId, conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }

        Character character = conversation.getCharacter();
        List<CharacterMessage> messages = messageRepository.findByCharacterConversation_CharacterConversationIdOrderByTimestamp(conversationId);

        return convertToConversationDTO(conversation, character, messages);
    }

    // 获取用户的所有对话
    public Page<CharacterConversationDTO> getUserConversations(Long userId, Pageable pageable) {
        Page<CharacterConversation> conversations = conversationRepository.findByUser_Id(userId, pageable);
        return conversations.map(conv -> {
            Character character = conv.getCharacter();
            return convertToConversationDTO(conv, character);
        });
    }

    // 获取用户与特定角色的所有对话
    public Page<CharacterConversationDTO> getUserConversationsByCharacter(Long userId, Long characterId, Pageable pageable) {
        Page<CharacterConversation> conversations = conversationRepository.findByUser_IdAndCharacter_CharacterId(userId, characterId, pageable);
        return conversations.map(conv -> {
            Character character = conv.getCharacter();
            return convertToConversationDTO(conv, character);
        });
    }

    // 删除对话
    @Transactional
    public void deleteConversation(Long userId, Long conversationId) {
        CharacterConversation conversation = conversationRepository.findByUser_IdAndCharacterConversationId(userId, conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }

        messageRepository.deleteByCharacterConversation_CharacterConversationId(conversationId);
        conversationRepository.delete(conversation);
    }

    // 构建角色设定提示
    private String buildCharacterPrompt(Character character) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("角色设定：\n");
        prompt.append("姓名：").append(character.getName()).append("\n");
        if (character.getAge() != null) {
            prompt.append("年龄：").append(character.getAge()).append("\n");
        }
        if (character.getPersonality() != null) {
            prompt.append("性格：").append(character.getPersonality()).append("\n");
        }
        if (character.getOccupation() != null) {
            prompt.append("职业：").append(character.getOccupation()).append("\n");
        }
        if (character.getBackground() != null) {
            prompt.append("背景：").append(character.getBackground()).append("\n");
        }
        if (character.getRelationships() != null) {
            prompt.append("人物关系：").append(character.getRelationships()).append("\n");
        }
        if (character.getLanguageStyle() != null) {
            prompt.append("语言风格：").append(character.getLanguageStyle()).append("\n");
        }
        return prompt.toString();
    }

    // 构建对话历史
    private String buildConversationHistory(List<CharacterMessage> messages) {
        StringBuilder history = new StringBuilder();
        for (CharacterMessage message : messages) {
            history.append(message.getSenderType() == CharacterMessage.SenderType.user ? "用户：" : "角色：")
                  .append(message.getContent())
                  .append("\n");
        }
        return history.toString();
    }

    // 调用千问模型
    private String callQwenPlusCharacter(String characterPrompt, String conversationHistory, String userMessage) {
        return qwenApiService.generateResponse(characterPrompt, conversationHistory, userMessage);
    }

    // 转换为会话DTO
    private CharacterConversationDTO convertToConversationDTO(CharacterConversation conversation, Character character) {
        return convertToConversationDTO(conversation, character, null);
    }

    // 转换为会话DTO（包含消息）
    private CharacterConversationDTO convertToConversationDTO(CharacterConversation conversation, Character character, List<CharacterMessage> messages) {
        CharacterConversationDTO dto = new CharacterConversationDTO();
        dto.setCharacterConversationId(conversation.getCharacterConversationId());
        dto.setUserId(conversation.getUser().getId());
        dto.setCharacterId(character.getCharacterId());
        dto.setTitle(conversation.getTitle());
        dto.setSceneContext(conversation.getSceneContext());
        dto.setCreatedAt(conversation.getCreatedAt());
        
        // 设置角色信息
        CharacterDTO characterDTO = new CharacterDTO();
        characterDTO.setCharacterId(character.getCharacterId());
        characterDTO.setName(character.getName());
        characterDTO.setAge(character.getAge());
        characterDTO.setPersonality(character.getPersonality());
        characterDTO.setOccupation(character.getOccupation());
        dto.setCharacter(characterDTO);

        // 设置消息列表
        if (messages != null) {
            List<CharacterMessageDTO> messageDTOs = messages.stream()
                .map(this::convertToMessageDTO)
                .collect(Collectors.toList());
            dto.setMessages(messageDTOs);
        }

        return dto;
    }

    // 转换为消息DTO
    private CharacterMessageDTO convertToMessageDTO(CharacterMessage message) {
        CharacterMessageDTO dto = new CharacterMessageDTO();
        dto.setCharacterMessageId(message.getCharacterMessageId());
        dto.setCharacterConversationId(message.getCharacterConversation().getCharacterConversationId());
        dto.setSenderType(message.getSenderType().toString());
        dto.setContent(message.getContent());
        dto.setAudioUrl(message.getAudioUrl());
        dto.setTimestamp(message.getTimestamp());
        return dto;
    }

    // 获取或创建对话
    @Transactional
    public CharacterConversationDTO getOrCreateConversation(Long userId, Long characterId) {
        // 查找现有对话
        List<CharacterConversation> conversations = conversationRepository.findByUser_IdAndCharacter_CharacterId(userId, characterId);
        CharacterConversation conversation;
        
        if (conversations.isEmpty()) {
            // 如果没有现有对话，创建新对话
            Character character = characterRepository.findByUser_IdAndCharacterId(userId, characterId);
            if (character == null) {
                throw new RuntimeException("角色不存在");
            }
            User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

            conversation = new CharacterConversation();
            conversation.setUser(user);
            conversation.setCharacter(character);
            conversation.setTitle("新对话");
            conversation = conversationRepository.save(conversation);
        } else {
            // 使用最新的对话
            conversation = conversations.get(0);
        }

        // 获取消息历史
        List<CharacterMessage> messages = messageRepository.findByCharacterConversation_CharacterConversationIdOrderByTimestampDesc(conversation.getCharacterConversationId());
        return convertToConversationDTO(conversation, conversation.getCharacter(), messages);
    }
} 